package engineer.reverse.java;

import design_patterns.command.Command;
import engineer.TypesMapper;
import entity_model.Entity;
import entity_model.EntityModel;
import utils.titles.Title;

import java.lang.reflect.Field;

/**
 * Created by nuno-rafael-figueiredo on 11-07-2014.
 */
public class RevertField extends Command{
    private final Entity entity;
    private final Field field;

    public RevertField(Entity entity, Field field) {
        this.entity = entity;
        this.field = field;
    }

    @Override
    public void execute() {
        logger.info(field.getName());
        Class<?> type = field.getType();

        EntityModel model = entity.getModel();
        if (type.isArray()) {
            Entity other = model.getEntity(Title.fromClass(type.getComponentType()));
            entity.hasMany(other, Title.fromLowerCamel(field.getName()));
        } else {
            if (type.getPackage().getName().equals(model.getTitle().toSnakeCase())) {
                Entity other = model.getEntity(Title.fromClass(type));
                entity.hasOne(other, Title.fromLowerCamel(field.getName()));
            } else {
                entity.createAttribute(TypesMapper.toDataType(type), Title.fromLowerCamel(field.getName()));
            }
        }

        finish();
    }
}
